package com.tanhua.server.service;

import cn.hutool.core.collection.CollectionUtil;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.autoconfig.template.SmsTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.dubbo.api.*;
import com.tanhua.model.domain.User;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.UserLike;
import com.tanhua.model.mongo.Visitors;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.Duration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserService {

    @Autowired
    private SmsTemplate template;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @DubboReference
    private UserApi userApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @Autowired
    private UserFreezeService userFreezeService;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private MqMessageService mqMessageService;

    @DubboReference
    private UserLikeApi userLikeApi;
    @DubboReference
    private FriendApi friendApi;
    @DubboReference
    private UserInfoApi userInfoApi;
    @DubboReference
    private VisitorsApi visitorsApi;

    /**
     * 发送短信验证码
     *
     * @param phone
     */
    public void sendMsg(String phone) {
        //根据手机号查询用户，如果用户存在，判断是否被冻结
        User user = userApi.findByMobile(phone);
        if (user != null) {
            userFreezeService.checkUserStatus("1", user.getId());
        }

        //1、随机生成6位数字
        //String code = RandomStringUtils.randomNumeric(6);
        String code = "123456";
        //2、调用template对象，发送手机短信
        //template.sendSms(phone,code);
        //3、将验证码存入到redis
        redisTemplate.opsForValue().set("CHECK_CODE_" + phone, code, Duration.ofMinutes(5));
    }


    /**
     * 验证登录
     *
     * @param phone
     * @param code
     */
    public Map loginVerification(String phone, String code) {
        //1、从redis中获取下发的验证码
        String redisCode = redisTemplate.opsForValue().get("CHECK_CODE_" + phone);
        //2、对验证码进行校验（验证码是否存在，是否和输入的验证码一致）
        if (StringUtils.isEmpty(redisCode) || !redisCode.equals(code)) {
            //验证码无效
            throw new BusinessException(ErrorResult.loginError());
        }
        //3、删除redis中的验证码
        redisTemplate.delete("CHECK_CODE_" + phone);
        //4、通过手机号码查询用户
        User user = userApi.findByMobile(phone);
        boolean isNew = false;
        //5、如果用户不存在，创建用户保存到数据库中
        String type = "0101";//登录
        if (user == null) {
            type = "0102";//注册
            user = new User();
            user.setMobile(phone);
            user.setPassword(DigestUtils.md5Hex("123456"));
            Long userId = userApi.save(user);
            user.setId(userId);
            isNew = true;

            //注册环信用户
            String hxUser = "hx" + user.getId();
            Boolean create = huanXinTemplate.createUser(hxUser, Constants.INIT_PASSWORD);
            if (create) {
                user.setHxUser(hxUser);
                user.setHxPassword(Constants.INIT_PASSWORD);
                userApi.update(user);
            }
        }

        mqMessageService.sendLogMessage(user.getId(), type, "user", null);

        //6、通过JWT生成token(存入id和手机号码)
        Map tokenMap = new HashMap();
        tokenMap.put("id", user.getId());
        tokenMap.put("mobile", phone);
        String token = JwtUtils.getToken(tokenMap);
        //7、构造返回值
        Map retMap = new HashMap();
        retMap.put("token", token);
        retMap.put("isNew", isNew);

        return retMap;
    }

    /**
     * 发送验证码
     */
    public void sendVerificationCode() {

        String mobile = UserHolder.getMobile();
//        String code = RandomStringUtils.randomNumeric(6);
        String code = "123456";
//        if (mobile != null){
//            smsTemplate.sendSms(mobile, code);
//        }

        redisTemplate.opsForValue().set("CHECK_CODE" + mobile, code);

    }

    // 校验验证码
    public Boolean checkVerificationCode(String verificationCode) {

        String mobile = UserHolder.getMobile();
        String code = redisTemplate.opsForValue().get("CHECK_CODE" + mobile);
        if (verificationCode == null) {
            throw new BusinessException(ErrorResult.error());
        }
        if (verificationCode.equals(code)) {
            return true;
        } else {
            return false;
        }


    }

    /**
     * 保存手机号码
     *
     * @param phone
     */
    public void savePhone(String phone) {

        String mobile = UserHolder.getMobile();
        User user = userApi.findByMobile(mobile);
        if (user != null) {
            user.setMobile(phone);
            userApi.updateById(user);
        }
    }

    /*
     * 互相喜欢，喜欢，粉丝 - 统计
     * */
    //我喜欢的数据统计
    public Integer counts() {
        Long userId = UserHolder.getUserId();
        Integer userlike = Math.toIntExact(userLikeApi.counts(userId));
        return userlike;
    }

    //粉丝数据统计
    public Integer fanCounts() {
        Long userId = UserHolder.getUserId();
        Integer fancounts = userLikeApi.fanCounts(userId);
        return fancounts;
    }

    //互相喜欢数据统计
    public Integer eachLoveCount() {

        Long userId = UserHolder.getUserId();
        Integer eachelocvecount = friendApi.eachLoveCount(userId);
        return eachelocvecount;
    }

    //查询互相喜欢，喜欢，粉丝列表
    public PageResult findLove(Integer type, String nickname, Integer page, Integer pagesize) {
        Long userId = UserHolder.getUserId();
        //判断类型互相喜欢
        if (type == 1) {
            //查询好友
            List<Friend> list = friendApi.eachLove(userId);
            if (CollectionUtil.isEmpty(list)) {
                return new PageResult();
            }
            //获取好友id集合
            List<Long> ids = CollectionUtil.getFieldValues(list, "friendId", Long.class);
            //根据好友id查询好友详情
            PageResult pageResult = userInfoApi.findUserByIds(page, pagesize, ids, nickname);
            return pageResult;
        }
        //喜欢
        if (type == 2) {
            List<UserLike> iLike = userLikeApi.lLove(userId);
            if (CollectionUtil.isEmpty(iLike)) {
                return null;
            }
            List<Long> likeUserId = CollectionUtil.getFieldValues(iLike, "likeUserId", Long.class);
            PageResult pageResult = userInfoApi.findUserByIds(page, pagesize, likeUserId, nickname);
            return pageResult;
        }
        //粉丝
        if (type == 3) {
            List<UserLike> loveMe = userLikeApi.loveMe(userId);
            List<Long> loveMeId = CollectionUtil.getFieldValues(loveMe, "userId", Long.class);
            if (CollectionUtil.isEmpty(loveMeId)) {
                return null;
            }
            PageResult pageResult = userInfoApi.findUserByIds(page, pagesize, loveMeId, nickname);

            return pageResult;

        }
        if (type == 4) {
            //访客集合
            List<Visitors> visitors = visitorsApi.findById(userId);
            List<Long> visitorUserId = CollectionUtil.getFieldValues(visitors, "visitorUserId", Long.class);
            if (CollectionUtil.isEmpty(visitorUserId)) {
                return null;
            }
            PageResult pageResult = userInfoApi.findUserByIds(page, pagesize, visitorUserId, nickname);

            return pageResult;
        }


        PageResult pageResult = new PageResult();
        return pageResult;
    }

    //取消喜欢
    public void update(Long uid) {
        Long userId = UserHolder.getUserId();
        userLikeApi.update(uid, userId);

    }

    //喜欢粉丝
    public void like(Long uid) {
        Long userId = UserHolder.getUserId();
        userLikeApi.like(userId, uid);
    }
}
